# -*- coding: utf-8 -*-
"""
created on 2017/12/7 14:47

@author: didichen
"""

# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/hockey.html
import requests
import zipfile
import os
import re


def download_zip(url):
    # 解密过程：下载http://www.pythonchallenge.com/pc/def/channel.zip
    r = requests.get(url)
    with open("channel.zip", "wb") as fr:
        fr.write(r.content)


def un_zip(file_name):
    """unzip zip file"""
    zip_file = zipfile.ZipFile(file_name)
    # 创建目录
    if os.path.isdir(file_name + "_files"):
        pass
    else:
        os.mkdir(file_name + "_files")
    # 解压缩
    for names in zip_file.namelist():
        zip_file.extract(names, file_name + "_files/")
    zip_file.close()


def read_file(file_path, zip_name, first_number):
    comments = []
    zip_file = zipfile.ZipFile(zip_name)
    p = re.compile(r"Next nothing is (\d+)")
    # 读取文件内容
    while True:
        with open(file_path + '/' + first_number + '.txt', 'r') as fr:
            # Next nothing is 45243
            first_number_list = p.findall(fr.readline())
            # 提取每个comments的内容，并将byte类型转为str类型
            comments.append(str(zip_file.getinfo(first_number + '.txt').comment, encoding='utf-8'))
            if first_number_list:
                first_number = first_number_list[0]
            else:
                break
    print("".join(comments))


if __name__ == '__main__':
    # download_zip('http://www.pythonchallenge.com/pc/def/channel.zip')
    # un_zip('channel.zip')
    read_file(file_path='channel.zip_files', zip_name='channel.zip', first_number='90052')
